using System;
using System.Windows.Forms;
using StudentManagementLibrary;

namespace StudentManagementApp
{
    public partial class MainForm : Form
    {
        private StudentManagementContext _context;

        public MainForm()
        {
            InitializeComponent();
            _context = new StudentManagementContext();
            _context.Database.EnsureCreated();
        }

        private void btnAddSchool_Click(object sender, EventArgs e)
        {
            var school = new School { Name = txtSchoolName.Text };
            _context.Schools.Add(school);
            _context.SaveChanges();
            LogOperation("Added School: " + school.Name);
        }

        private void btnAddClass_Click(object sender, EventArgs e)
        {
            var schoolId = int.Parse(txtSchoolId.Text);
            var className = txtClassName.Text;
            var classEntity = new Class { Name = className, SchoolId = schoolId };
            _context.Classes.Add(classEntity);
            _context.SaveChanges();
            LogOperation("Added Class: " + className);
        }

        private void btnAddStudent_Click(object sender, EventArgs e)
        {
            var classId = int.Parse(txtClassId.Text);
            var studentName = txtStudentName.Text;
            var student = new Student { Name = studentName, ClassId = classId };
            _context.Students.Add(student);
            _context.SaveChanges();
            LogOperation("Added Student: " + studentName);
        }

        private void LogOperation(string operation)
        {
            var log = new Log { Operation = operation, Timestamp = DateTime.Now };
            _context.Logs.Add(log);
            _context.SaveChanges();
        }

        private void btnViewLogs_Click(object sender, EventArgs e)
        {
            var logs = _context.Logs.ToList();
            lstLogs.Items.Clear();
            foreach (var log in logs)
            {
                lstLogs.Items.Add($"{log.Timestamp}: {log.Operation}");
            }
        }
    }
}